package com.ysd.service.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class IBeanUtils extends BeanUtils {
    public static <R> List<R> copyProperties(List entityList, Class<R> rClass) {
        List<R> responsesList = new ArrayList<>();
        if (entityList != null)
        entityList.stream().forEach(entity -> {
            try {
                R re = (R) Class.forName(rClass.getName()).newInstance();
                BeanUtils.copyProperties(entity, re);
                responsesList.add(re);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return responsesList;
    }
    public static  <R> R copyProperties(Object entity, Class<R> rClass) {
        R re = null;
        try {
            re = (R) Class.forName(rClass.getName()).newInstance();

        } catch (Exception e) {
            e.printStackTrace();
        }
        if (entity!=null)
        BeanUtils.copyProperties(entity, re);
        return re;
    }
    //Map转Object
    public static <R> R mapToObject(Map<String, Object> map, Class<R> rClass) throws IllegalAccessException {
        if (map == null)
            return null;
        R re = null;
        try {
            re = (R) Class.forName(rClass.getName()).newInstance();

        } catch (Exception e) {
            e.printStackTrace();
        }
        Field[] fields = re.getClass().getDeclaredFields();
        for (Field field : fields) {
            int mod = field.getModifiers();
            if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                continue;
            }
            field.setAccessible(true);
            if (map.containsKey(field.getName())) {
                //业务需求特殊处理
                if ("class java.math.BigDecimal".equals(field.getGenericType().toString())){
                    field.set(re, new BigDecimal(map.get(field.getName())+""));
                }else{
                    field.set(re, map.get(field.getName()));
                }
            }
        }
        return re;
    }
    //Object转map
    public static <T> Map<String,Object>  objectTomap(T findArchiveDto){
        Map<String,Object> map = JSONObject.parseObject(JSON.toJSONString(findArchiveDto));
        return map;
    }
}
